package com.hctforgreen.greenservice.utils;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import com.hctforgreen.greenservice.model.PersonPotinsEntity;

/**
 * User points 存储Util
 * 
 * @author Tallen Zhai
 * 
 */
public class PersonPointsStoreUtil {

	/**
	 * 保存userInfo
	 * 
	 * @param activity
	 */
	public static void save(Context context, PersonPotinsEntity entity) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(
				HctConstants.PERSON_POINTS_STORE_FILE_NAME,
				Context.MODE_WORLD_WRITEABLE);
		Editor editor = sharedPreferences.edit();

		String userInfo = change2String(entity);
		editor.putString(HctConstants.PERSON_POINTS_STORE_KEY_VALUE, userInfo);
		editor.commit();
	}

	/**
	 * 删除userInfo
	 * 
	 * @param activity
	 */
	public static void delete(Activity activity) {
		SharedPreferences sharedPreferences = activity.getSharedPreferences(
				HctConstants.PERSON_POINTS_STORE_FILE_NAME,
				Context.MODE_WORLD_WRITEABLE);
		Editor editor = sharedPreferences.edit();

		// String userInfo = change2String(entity);
		editor.putString(HctConstants.PERSON_POINTS_STORE_KEY_VALUE, "");
		// editor.remove(HctConstants.LOGIN_RESULT_STORE_KEY_VALUE);
		// editor.remove(key)
		editor.commit();
	}

	private static String change2String(PersonPotinsEntity entity) {
		String sLoginResult = "";
		sLoginResult = entity.points + ";" + entity.rating + ";" + entity.rank;
		return sLoginResult;
	}

	/**
	 * 获取userInfo
	 * 
	 * @param activity
	 * @return
	 */
	public static PersonPotinsEntity get(Activity activity) {
		SharedPreferences sharedPreferences = activity.getSharedPreferences(
				HctConstants.PERSON_POINTS_STORE_FILE_NAME,
				Context.MODE_WORLD_WRITEABLE);
		String sLoginResult = sharedPreferences.getString(
				HctConstants.PERSON_POINTS_STORE_KEY_VALUE, "");
		return change2Entity(sLoginResult);
	}

	private static PersonPotinsEntity change2Entity(String sLoginResult) {
		String[] strings = sLoginResult.split(";");
		PersonPotinsEntity entity = new PersonPotinsEntity();
		if (strings != null && strings.length > 2) {//
			entity.points = strings[0];
			entity.rating = strings[1];
			entity.rank = strings[2];
		}
		return entity;
	}

}
